<!--
* description: 基础数据-故障原因码
* author: wangjuan
* createdDate: 2021-5-6
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="false"
      :dynamic-is-init-table="true"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible.sync="editPopupsVisible"
      :popups-state="editPopupsState"
    />
  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/se/apiBaseData'
import { exportExcel } from '@/utils/getTimeString.js'

export default {
  name: 'FinancialMonthlyMaintenance',

  components: {
    OneTableTemplate,
    Edit: () => import('./edit')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      editRowData: {},
      editPopupsVisible: false,

      // 网格查询API配置对象
      apiConfig: api.queryFaultRcPage,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'add',
          clickEvent: this.add,
          text: this.$t('sys.button.add'), // 新增
          position: 'left'
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          name: 'importTemplate',
          icon: 'iconfont icon-importTemplate',
          clickEvent: () => this.handFileListChange(),
          text: '导入',
          position: 'upload'
        },
        {
          compKey: 'btnKey5',
          type: 'text',
          size: 'small',
          name: 'importTemplateDownload',
          icon: 'iconfont  icon-importTemplateDownload',
          click: () => this.templateDownload(),
          text: '导入模板下载',
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '故障原因码：',
              codeField: 'faultRcCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '故障原因码名称：',
              codeField: 'faultRcName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'updateControlId',
              label: '并发控制字段',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'faultRcId',
              label: '故障原因码ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn1',
              label: '操作',
              width: 150,
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '修改',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.edit(index)
                },
                {
                  compKey: 'propKey2',
                  labelName: '删除',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.deleteData(index)
                }
              ]
            },
            {
              prop: 'faultRcCode',
              label: '故障原因码'
            },
            {
              prop: 'faultRcName',
              label: '故障原因码名称'
            },
            {
              prop: 'remark',
              label: '备注'
            }
          ],

      // 表单查询数据
      formField: this.$utils.getFormField(this, {
        faultRcCode: '',
        faultRcName: '',
        faultRcId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    // 编辑获取数据
    edit(index) {
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
      this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
    },

    add() {
      this.editPopupsState = 'add'
      this.editPopupsVisible = true
    },
    deleteData(index) {
      const that = this
      this.$confirm('确定要删除吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const queryObj = {
        // 保存mutation
          type: 'mutation',
          // api配置
          apiConfig: api.delFaultRc,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
            updateControlId: that.$refs.multipleTable.list[index].updateControlId,
            faultRcId: that.$refs.multipleTable.list[index].faultRcId
          }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        // 调用中台API方法（可复用）
        this.$requestAPI(paramD).then(response => {
          if (response.result === '1') {
            this.$message({
              message: response.msg,
              type: 'success',
              duration: 1000
            })
            this.$nextTick(() => {
              this.$refs.multipleTable.queryTable(1)
            })
          } else {
            this.$message({
              message: response.msg,
              type: 'warn',
              duration: 1000
            })
          }
        }).catch(err => {
          console.log(err)
        })
      })
    },

    // 模板下载
    templateDownload() {
    //   this.$requestAPI({
    //     variables: { dataType: 'excel' },
    //     apiUrl: api.importFaultRcTemplate.APIUrl
    //   }).then(res => {
    //     this.$utils.downloadFile(res, '故障原因导入模板.xlsx')
    //   })
      exportExcel(this.formField, api.importFaultRcTemplate.APIUrl, '', '故障原因导入模板')
    },

    // 导入
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType !== 'xls' && fileType !== 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const that = this
      const url = api.importFaultRcExcel.APIUrl
      that.$requestUpload(url, param).then(response => {
        loading.close()
        if (response.result === '1') {
          this.$message({
            message: '导入成功',
            type: 'success'
          })
          that.queryTable(1)
        } else {
          this.$message({
            message: response.msg,
            type: 'warning'
          })
        }
      }).catch(_ => {})
    }
  }
}
</script>
